package com.chuangyang.fixboxmaster.ui.fragment;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.android.volley.Response;
import com.chuangyang.fixboxlib.utils.StringUtils;
import com.chuangyang.fixboxlib.widgets.ImageButton;
import com.chuangyang.fixboxmaster.R;
import com.chuangyang.fixboxmaster.bean.ChangePriceEvent;
import com.chuangyang.fixboxmaster.bean.OrderDetail;
import com.chuangyang.fixboxmaster.service.FixBoxApi;
import com.chuangyang.fixboxmaster.service.GsonRequest;
import com.chuangyang.fixboxmaster.ui.ApplianceInfoActivity;
import com.chuangyang.fixboxmaster.ui.CompleteApplianceInfoActivity;
import com.chuangyang.fixboxmaster.ui.MapViewActivity;
import com.chuangyang.fixboxmaster.ui.ModuleActivity;
import com.chuangyang.fixboxmaster.ui.PayActivity;

import java.util.HashMap;

import de.greenrobot.event.EventBus;

/**
 * Created by vanshu on 15/4/10 14:03.
 */
public class OrderDetailFragment extends BaseFragment implements View.OnClickListener {
    private View mContentView;
    private LinearLayout mOrderStatusLayout;
    private TextView mOrderStatus;
    private TextView mOrderId;
    private TextView mOrderType;
    private TextView mOrderNum;
    private TextView mOrderDes;
    private TextView mOrderUserName;
    private TextView mOrderAppointTime;
    private TextView mOrderAddress;
    private ImageButton mDialPhone;
    private ImageButton mChangePrice;
    private String orderId;
    private String phoneNumber;
    private Button mBtnBottom;
    private int currentOrderStatus;
    private static final int ACTIVITY_INTENT_GET_PRICE = 10;
    private OrderDetail orderDetail;
    private LinearLayout mRepairSuccLin;
    private TextView mPriceView;

    public static final int REQUEST_CODE_PAY = 5;
    public static final int RESULT_CODE_PAY_OK = 6;
    private int transctionId;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        mContentView = inflater.inflate(R.layout.fragment_order_detail, container, false);
        orderId = getArguments().getString(ModuleActivity.ORDER_ID);
        mOrderStatusLayout = (LinearLayout) mContentView.findViewById(R.id.order_status_layout);
        mOrderStatus = (TextView) mContentView.findViewById(R.id.order_status);
        mOrderId = (TextView) mContentView.findViewById(R.id.order_id);
        mOrderType = (TextView) mContentView.findViewById(R.id.order_repair_type);
        mOrderNum = (TextView) mContentView.findViewById(R.id.order_repair_num);
        mOrderDes = (TextView) mContentView.findViewById(R.id.order_des);
        mOrderUserName = (TextView) mContentView.findViewById(R.id.order_user_name);
        mDialPhone = (ImageButton) mContentView.findViewById(R.id.btn_dial);
        mChangePrice = (ImageButton) mContentView.findViewById(R.id.btn_change_price);
        mDialPhone.setOnClickListener(this);
        mChangePrice.setOnClickListener(this);
        mOrderAppointTime = (TextView) mContentView.findViewById(R.id.order_appoint_time);
        mOrderAddress = (TextView) mContentView.findViewById(R.id.order_user_address);
        mBtnBottom = (Button) mContentView.findViewById(R.id.btn_bottom);
        mBtnBottom.setOnClickListener(this);
        mRepairSuccLin = (LinearLayout) mContentView.findViewById(R.id.repair_succ_lin);
        mPriceView = (TextView) mContentView.findViewById(R.id.order_repair_price);
        LinearLayout mOrderAddressLayout = (LinearLayout) mContentView.findViewById(R.id.ll_order_user_address);
        mOrderAddressLayout.setOnClickListener(this);

        try {
            transctionId = Integer.parseInt(getArguments().getString(ModuleActivity.TRANSCATION_ID));
        }catch (Exception e){
            transctionId=-1;
        }
        return super.onCreateView(inflater, container, savedInstanceState);
    }

    @Override
    public void onActivityCreated(@Nullable Bundle savedInstanceState) {
        super.onActivityCreated(savedInstanceState);
        setContentView(mContentView);
        loadData();
    }

    private void loadData() {
        HashMap<String, String> param = new HashMap<>();
        param.put("id", orderId);
        addRequest(new GsonRequest<>(FixBoxApi.ORDER_DETAIL, param, OrderDetail.class, responseListener));
    }

    private Response.Listener<OrderDetail> responseListener = new Response.Listener<OrderDetail>() {
        @Override
        public void onResponse(OrderDetail response) {
            if (getActivity() != null && isAdded()) {
                orderDetail = response;
                mOrderId.setText("" + response.result.orderId);
                if (response.result.skill != null) {
                    mOrderType.setText(response.result.skill.title);
                    mOrderNum.setText("×" + response.result.num);
                }
                if (response.result.orderDes == null || response.result.orderDes.equals("")) {
                    mOrderDes.setVisibility(View.GONE);
                } else {
                    mOrderDes.setText(response.result.orderDes);
                }
                if (response.result.address != null) {
                    mOrderUserName.setText(response.result.address.nickName);
                    if (response.result.address.address2 == null) {
                        mOrderAddress.setText(response.result.address.address1);
                    } else {
                        mOrderAddress.setText(response.result.address.address1 + response.result.address.address2);
                    }
                    phoneNumber = response.result.address.phoneNumber;
                }
                mOrderAppointTime.setText(response.result.appointTime);
                getCurrentState(response.result.orderStatus);
                if (response.result.extraPrice > 0) {
                    mPriceView.setText(response.result.serviceFeeToMaster + "元" + "(含补贴" + response.result.extraPrice + "元)");
                } else {
                    mPriceView.setText(response.result.serviceFeeToMaster + "元");
                }
                transctionId=response.result.transactionId;
                showResult();
            }
        }
    };


    @Override
    public void onStop() {
        super.onStop();
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_dial:
                StringUtils.dialPhone(getActivity(), phoneNumber);
                break;

            case R.id.btn_bottom:
                if (currentOrderStatus == 10) {
                    takeOrder();
                } else if (currentOrderStatus == 20 && transctionId == 9) {
                    HashMap<String, String> param = new HashMap<>();
                    param.put("id", orderId);
                    addRequest(new GsonRequest<>(FixBoxApi.GET_RECYCER_ORDER_FINISH, param, OrderDetail.class, responseListener));
//                    Toast.makeText(getActivity(), "finish the order with recycler", Toast.LENGTH_SHORT).show();
                } else if (currentOrderStatus == 20) {
                    Intent intent = new Intent(getActivity(), CompleteApplianceInfoActivity.class);
                    Bundle bundle = new Bundle();
                    bundle.putString("order_id", "" + orderDetail.result.id);
                    bundle.putInt("order_num", orderDetail.result.num);
                    if (orderDetail.result != null)
                        bundle.putString("skill_id", orderDetail.result.skillId);
                    bundle.putInt(ApplianceInfoActivity.TRANSCATION_ID, orderDetail.result.transactionId);
                    intent.putExtras(bundle);
                    startActivityForResult(intent, ACTIVITY_INTENT_GET_PRICE);
                }
                break;
            case R.id.ll_order_user_address:
                Intent intent = new Intent();
                intent.putExtra("address", orderDetail.result.address);
                intent.setClass(getActivity(), MapViewActivity.class);
                startActivity(intent);
                break;

            case R.id.btn_change_price:
                Intent intent2 = new Intent(getActivity(), CompleteApplianceInfoActivity.class);
                Bundle bundle = new Bundle();
                bundle.putString("order_id", "" + orderDetail.result.id);
                bundle.putInt("order_num", orderDetail.result.num);
                if (orderDetail.result != null)
                    bundle.putString("skill_id", orderDetail.result.skillId);
                bundle.putInt(ApplianceInfoActivity.TRANSCATION_ID, orderDetail.result.transactionId);
                intent2.putExtras(bundle);
                startActivityForResult(intent2, ACTIVITY_INTENT_GET_PRICE);
                ChangePriceEvent changePriceEvent = new ChangePriceEvent();
                changePriceEvent.isReprice = 1; //表示
                EventBus.getDefault().postSticky(changePriceEvent);
                break;
        }
    }



    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == ACTIVITY_INTENT_GET_PRICE) {
            if (resultCode == Activity.RESULT_OK) {
                String price = data.getStringExtra("price");
                confirmOrderPrice(price);
            }
        } else if (requestCode == REQUEST_CODE_PAY) {
            if (resultCode == RESULT_CODE_PAY_OK) {
                loadData();
            }
        }
    }

    private void confirmOrderPrice(String price) {
        HashMap<String, String> param = new HashMap<>();
        param.put("id", orderId);
        param.put("totalPrice", price);
        addRequest(new GsonRequest<>(FixBoxApi.ORDER_CONFIRM_ORDER, param, OrderDetail.class, responseListener));
    }


    private void takeOrder() {
        HashMap<String, String> param = new HashMap<>();
        param.put("id", orderId);
        addRequest(new GsonRequest<>(FixBoxApi.ORDER_TAKE_ORDER, param, OrderDetail.class, responseListener));
    }

    private void getCurrentState(int status) {
        // 10 创建成功, 同时也是下单成功等待接单
        // 11 正在等待分配中,这个时候订单不一定完成填写完毕,可以由客服填写.
        // 20   订单已受理  师傅已经接单  用户还没付款
        // 30 师傅完成维修,并写了价目表
        // 40 用户已付款
        // 50 订单完成
        // 60
        // 订单取消
        // 1000 是创建后就取消
        // 1001 是等待分配中取消
        // 1002 是师已经接单但没写维修记录
        // 1003 是师已经接单但了写维修记录
        // 1004 是用户付款后取消
        // 1099 是未知的取消 状态40之前是可以取消的
        if (status == 10) {
            currentOrderStatus = status;
            moveToState0();
            setHasOptionsMenu(false);
        } else if (transctionId == 9 && status == 20) {
            currentOrderStatus = status;
            moveToRecycleState();
            setHasOptionsMenu(false);
        } else if (status == 20) {
            currentOrderStatus = status;
            moveToState1();
            setHasOptionsMenu(false);
        } else if (status == 30) {
            currentOrderStatus = status;
            moveToState2();
            setHasOptionsMenu(true);
        } else if (status == 40 || status == 50 || status == 60) {
            currentOrderStatus = status;
            moveToState3();
            setHasOptionsMenu(false);
        } else if (status > 1000) {
            currentOrderStatus = status;
            moveToStateCancel();
            setHasOptionsMenu(false);
        }
    }


    private void moveToState0() {  //等待接单
        mOrderStatusLayout.setVisibility(View.GONE);

        mDialPhone.setVisibility(View.GONE);

        mBtnBottom.setVisibility(View.VISIBLE);
        mBtnBottom.setText("接单");
        mRepairSuccLin.setVisibility(View.GONE);
        mChangePrice.setVisibility(View.GONE);
    }

    private void moveToState1() { //已接单，未维修完成
        mOrderStatusLayout.setVisibility(View.GONE);

        mDialPhone.setClickable(true);
        mDialPhone.setFocusable(true);
        mDialPhone.setBackgroundResource(R.drawable.blue_list_background_selector);
        mDialPhone.setVisibility(View.VISIBLE);

        mBtnBottom.setVisibility(View.VISIBLE);
        mBtnBottom.setText("报价");
        mRepairSuccLin.setVisibility(View.GONE);
        mChangePrice.setVisibility(View.GONE);
    }

    private void moveToState2() { //等待用户付款
        mOrderStatusLayout.setVisibility(View.VISIBLE);
        mOrderStatus.setText("等待用户付款");
        mOrderStatus.setTextColor(getResources().getColor(R.color.blue_background));

        mDialPhone.setClickable(true);
        mDialPhone.setFocusable(true);
        mDialPhone.setBackgroundResource(R.drawable.blue_list_background_selector);
        mDialPhone.setVisibility(View.VISIBLE);

        mBtnBottom.setVisibility(View.GONE);
        mRepairSuccLin.setVisibility(View.VISIBLE);
        mChangePrice.setVisibility(View.VISIBLE);
    }


    private void moveToState3() { //已完成订单
//        if(transctionId==9){
//            mOrderStatus.setText("订单已完成");
//        }else {
            mOrderStatus.setText("订单已完成，收到用户" + orderDetail.result.totalPrice + "元");
//        }


        mOrderStatusLayout.setVisibility(View.VISIBLE);
        mOrderStatus.setTextColor(getResources().getColor(R.color.blue_background));
        mOrderStatus.setVisibility(View.VISIBLE);

        mDialPhone.setClickable(true);
        mDialPhone.setFocusable(true);
        mDialPhone.setBackgroundResource(R.drawable.blue_list_background_selector);
        mDialPhone.setVisibility(View.VISIBLE);

        mBtnBottom.setVisibility(View.GONE);
        mChangePrice.setVisibility(View.GONE);
    }

    private void moveToStateCancel() { //已取消订单
        mOrderStatusLayout.setVisibility(View.VISIBLE);
        mOrderStatus.setText("订单已取消");

        mDialPhone.setClickable(false);
        mDialPhone.setFocusable(false);
        mDialPhone.setBackgroundResource(R.drawable.grey_list_background_selector);
        mDialPhone.setVisibility(View.VISIBLE);

        mBtnBottom.setVisibility(View.GONE);
        mRepairSuccLin.setVisibility(View.GONE);
    }


    private void moveToRecycleState() {
        mOrderStatusLayout.setVisibility(View.GONE);

        mDialPhone.setClickable(true);
        mDialPhone.setFocusable(true);
        mDialPhone.setBackgroundResource(R.drawable.blue_list_background_selector);
        mDialPhone.setVisibility(View.VISIBLE);

        mBtnBottom.setVisibility(View.VISIBLE);
        mBtnBottom.setText("完成维修");
        mRepairSuccLin.setVisibility(View.GONE);
        mChangePrice.setVisibility(View.GONE);
    }


    public void updateView() {
        loadData();
    }


    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        inflater.inflate(R.menu.order_detail_pay_menu, menu);
        super.onCreateOptionsMenu(menu, inflater);
    }


    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch (item.getItemId()) {
            case R.id.menu_pay:
                Intent intent = new Intent(getActivity(), PayActivity.class);
                Bundle bundle = new Bundle();
                bundle.putSerializable("order", orderDetail.result);
                intent.putExtras(bundle);
                startActivityForResult(intent, REQUEST_CODE_PAY);
                return true;
            default:
                return super.onOptionsItemSelected(item);
        }
    }


}
